﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Web;

namespace CSLive.Resources
{
    public class ResourceHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest( HttpContext context )
        {
            string[] parameters = context.Request.PathInfo.Remove( 0, 1 ).Split( new[] {'/'} );
            if ( parameters[ 0 ].ToLower().Equals( "image" ) )
            {
                string resourcetype = parameters[ 1 ];
                Assembly currentAssembly = Assembly.GetExecutingAssembly();
                string ext = Path.GetExtension( resourcetype ).Remove( 0, 1 ).ToLower();
                context.Response.ContentType = string.Format( "image/{0}", ext );
                Image img = Image.FromStream( currentAssembly.GetManifestResourceStream( resourcetype ) );
                if ( ext == "gif" ) img.Save( context.Response.OutputStream, ImageFormat.Gif );
                else if ( ext == "png" ) img.Save( context.Response.OutputStream, ImageFormat.Png );
                else img.Save( context.Response.OutputStream, ImageFormat.Jpeg );
            }
        }

        #endregion
    }
}